package com.demarc.pesquisas.infraestrutura.hibernate.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.usertype.UserType;

public abstract class BooleanNumberUserType implements UserType {

	private static final Integer SIM = 1;
	private static final Integer NAO = 0;
	private static final IntegerType INTEGER = new IntegerType();

	@Override
	public int[] sqlTypes() {
		return new int[] { getSQLType() };
	}

	public abstract int getSQLType();

	@Override
	@SuppressWarnings("rawtypes")
	public Class returnedClass() {
		return Boolean.class;
	}

	@Override
	public boolean equals(Object object1, Object object2)
			throws HibernateException {
		return object1 == object2 // NOPMD Need to compare the references
				|| (object1 != null && object2 != null && object1
						.equals(object2));
	}

	@Override
	public int hashCode(Object object) throws HibernateException {
		return object.hashCode();
	}

	private Boolean parse(Integer value) {
		Boolean result = null;

		if (value != null) {
			result = value.equals(NAO) ? false : true;
		}
		return result;
	}

	@Override
	public Object nullSafeGet(ResultSet inResultSet, String[] names,
			SessionImplementor session, Object owner)
			throws HibernateException, SQLException {
		Integer value = INTEGER.nullSafeGet(inResultSet, names[0], session);
		return parse(value);
	}

	private Integer toIntegerValue(Boolean val) {
		Integer result = null;

		if (val != null) {
			result = val ? SIM : NAO;
		}
		return result;
	}

	@Override
	public void nullSafeSet(PreparedStatement inPreparedStatement,
			Object object, int index, SessionImplementor session)
			throws HibernateException, SQLException {
		Integer val = toIntegerValue((Boolean) object);

		if (val == null) {
			inPreparedStatement.setNull(index, java.sql.Types.INTEGER);
		} else {
			inPreparedStatement.setInt(index, val);
		}
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Boolean) value;
	}

	@Override
	public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
		return cached;
	}

	@Override
	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return original;
	}
}
